package jp.co.cos.ittrick.channel.controller.client;

import java.util.List;

import jp.co.cos.ittrick.channel.model.CategoryModel;
import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.service.CategoryService;
import jp.co.cos.ittrick.channel.service.ChapterService;
import jp.co.cos.ittrick.channel.service.PageService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

public class DeleteCategoryController extends Controller {

    private CategoryService categoryService;
    private ChapterService chapterService;
    private PageService pageService;

    public DeleteCategoryController() {
        categoryService = new CategoryService();
        chapterService = new ChapterService();
        pageService = new PageService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String category = asString("category");

        // chapter page の削除
        CategoryModel categoryModel = categoryService.getCategoryByKey(Integer.valueOf(category));
        List<ChapterModel> chapterList = categoryModel.getChapterModelListRef().getModelList();
        for(ChapterModel chapterModel: chapterList) {

            // Pageの削除
            List<PageModel> pageList = chapterModel.getPageModelListRef().getModelList();
            for(PageModel pageModel: pageList) {
                pageService.delete((int)pageModel.getKeyString());
            }

            // Chapter の削除
            chapterService.delete((int)chapterModel.getKeyString());
        }

        // Delete
        categoryService.delete(Integer.valueOf(category));

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.getWriter().println("0");
        response.flushBuffer();

        return null;
    }
}
